//
//  TXTechnologyMenuListViewModel.swift
//  crm
//
//  Created by YiFang on 2024/6/13.
//

import UIKit
import HandyJSON

protocol TXTechnologyMenuListViewModelDelegate: NSObjectProtocol {
    func reloadData()
}

class TXTechnologyMenuListViewModel: NSObject {
    weak var delegate: TXTechnologyMenuListViewModelDelegate?
    var listArray: [TXTechnologyMenuListModel] = [], selList: [TXTechnologyMenuListModel] = []
    var selModel: TXTechnologyMenuListModel?
}

// MARK: - ******************  网络请求Api *******************
extension TXTechnologyMenuListViewModel {
    func setData() {
        DispatchQueue.global().async { [weak self] in
            guard let strongSelf = self else {
                return
            }
            strongSelf.getDataFromDB()
        }
    }
    
    // 解析数据
    private func getDataFromDB() {
        listArray.removeAll()
        //        1 data.json文件路径
        guard  let path = Bundle.main.path(forResource: "Data1", ofType: "json") else {
            print("出现错误!")
            return
        }
        let  url  = URL(fileURLWithPath: path)
        print(url)
        do {
            let data = try  Data(contentsOf: url)
            let json: Any = try  JSONSerialization.jsonObject(with: data, options: .mutableContainers)
            let jsonArray = json as? NSArray ?? []
            //            print(jsonArray)
            listArray  = JSONDeserializer<TXTechnologyMenuListModel>.deserializeModelArrayFrom(array: jsonArray) as? [TXTechnologyMenuListModel] ?? []
            selList = listArray // 将数组备份一份，当再次点击省份时不用再去json里拿
            listArray.first?.isSelect = true
            selModel = listArray.filter({ $0.isSelect == true }).first
            DispatchQueue.main.async {
                self.delegate?.reloadData()
            }
        } catch let error as Error? {
            print("读取本地数据出现错误!", error as Any)
        }
    }
    
    func findDirectory(in directories: [TXTechnologyMenuListModel], withName name: String) -> [TXTechnologyMenuListModel] {
        var arrar: [TXTechnologyMenuListModel] = []
        for model in directories {
            if model.id == name || model.pid == name {
                arrar.append(model)
                return arrar
            }
            let found = findDirectory(in: model.children, withName: name)
            arrar.append(contentsOf: found)
        }
        return arrar
    }
}
